<%@page import="java.util.Iterator"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.collections.ListUtils"%>
<%@page import="codeartist.json.JSONHandler"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.ArrayList"%>
<%@page import="org.apache.commons.lang.StringUtils"%>

<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@page import="org.apache.commons.io.FileUtils"%>
<%@page import="java.io.File"%>
<%@page import="com.gilstar.common.Constant"%>
<%@page import="org.apache.commons.codec.binary.Hex"%>
<%@page import="codeartist.ibatis.SQLManager"%>
<%@page import="org.slf4j.LoggerFactory"%>
<%@page import="org.slf4j.Logger"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8"%>
<%!
	private static Logger log = LoggerFactory.getLogger("FileUpload.jsp");
	
	private SQLManager sqlManager = SQLManager.getInstance();
		
	private ServletContext scx;
	private Hex h;
		
	private String path;
	
	private JSONHandler jsonHandler;
	
	private static final int MAX_FILE_SIZE = 104857600; // 100 M bytes
	private static final int MAX_THRESH_HOLD_SIZE = 104857600;

	public void jspInit()
	{
		try
		{
			path = Constant.UPLOAD_PATH;
			log.debug("upload path : {}", path);
		}
		catch(Exception e)
		{
			log.error("exception : {}", e.getMessage());
		}
	}
%>

<%

	jsonHandler = new JSONHandler();
	
	//if upload root directory exist?
	File file = new File(path);
	if(!file.exists())
	{
		FileUtils.forceMkdir(file);
	}
	
	DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setSizeThreshold(MAX_THRESH_HOLD_SIZE);
	factory.setRepository(new File(path));
	
	ServletFileUpload fu = new ServletFileUpload(factory);
	fu.setSizeMax(MAX_FILE_SIZE);
	
	if ( request.getContentLength() < fu.getSizeMax() )
	{
		try
		{
			List itemArr = fu.parseRequest(request);
			int nCount = itemArr.size();
			
			String performanceSeq = null;
			File currentDir = null;
			
			Iterator it = itemArr.iterator();
			
			List<Map<String, String>>fileList = new ArrayList<Map<String, String>>();
			
			while(it.hasNext())
			{
				FileItem item = (FileItem)it.next();
				if(item.isFormField())		//form field handle
				{
					if(StringUtils.equals(item.getFieldName(), Constant.PERFORMANCE_SEQ))
					{
						performanceSeq = item.getString(Constant.CV_UTF8);
						currentDir = new File(path, performanceSeq);
						FileUtils.forceMkdir(currentDir);
					}
				}
				else
				{
					int x = item.getName().lastIndexOf('\\');
					if ( x == -1 )
					{
						x = item.getName().lastIndexOf('/');
					}

					String filename = item.getName().substring(x+1);
					String ext = StringUtils.substringAfterLast(filename, Constant.DOT);
					item.write(new File(currentDir, filename));
					
					log.debug("filename : {}", filename);
					log.debug("ext : {}", ext);
					
					Map<String, String>param = new HashMap<String, String>();
					param.put(Constant.PERFORMANCE_SEQ, performanceSeq);
					param.put(Constant.FILE_NAME, filename);
					param.put(Constant.FILE_TYPE, ext);
					param.put(Constant.FILE_PATH, currentDir.getAbsolutePath());
					
					fileList.add(param);
				}
			}
			
			Map[] fileMap = new Map[fileList.size()];
			
			fileList.toArray(fileMap);
			
			try
			{
				sqlManager.startTransaction();
				
				boolean b = sqlManager.batch(Constant.SQLMAP_INSERT_PERFORMNACE_FILE, fileMap);
				
				if(b == Boolean.valueOf(true))
				{
					sqlManager.commitTransaction();
				}
				
			}
			catch(SQLException sqle)
			{
				throw new RuntimeException(sqle.getMessage());
			}
			finally
			{
				sqlManager.endTransaction();
			}
			
			String redirectionUrl = "http://gilstar.com/main/view.php?performance_seq=" + performanceSeq;
			
			response.sendRedirect(redirectionUrl);
		}
		catch (Exception e)
		{
			log.error("exception : {}", e);
			//go error page...
		}
	}
%>